package com.light.wanting.emoji.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.light.applet.common.config.CommonQiniuConfig;
import com.light.wanting.emoji.File;
import com.light.applet.common.config.QiniuConfig;
import com.light.wanting.emoji.mapper.FileMapper;
import com.light.wanting.emoji.service.FileService;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: 魏彪
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class FileServiceImpl extends ServiceImpl<FileMapper, File> implements FileService {

    @Autowired
    private QiniuConfig qiniuConfig;

    @Override
    public String upload(String filePath) throws IOException {

        // 创建上传token
//        Auth auth = Auth.create(qiniuConfig.getAccessKey(), qiniuConfig.getSecretKey());
//        String upToken = auth.uploadToken(qiniuConfig.getBucket());
//
//        // 设置上传配置，Region要与存储空间所属的存储区域保持一致
//        Configuration cfg = new Configuration(Region.huabei());
//
//        // 创建上传管理器
//        UploadManager uploadManager = new UploadManager(cfg);
//
//        List<java.io.File> fileList = allFiles(filePath);
//        System.out.println(fileList.size());
//
//        for (java.io.File file : fileList) {
//            FileInputStream fileInputStream = new FileInputStream(file);
//            Response response = uploadManager.put(fileInputStream, null, upToken, null, null);
//
//            System.out.println("response.statusCode = " + response.statusCode);
//        }

        return null;
    }

    @Override
    public String generateLink(String fileName, CommonQiniuConfig bucketInfo) {
        // 创建上传token
        Auth auth = Auth.create(qiniuConfig.getAccessKey(), qiniuConfig.getSecretKey());
        return auth.privateDownloadUrl(bucketInfo.getDomain() + fileName, bucketInfo.getExpires());
    }

    public static List<java.io.File> allFiles(String filePath) {
        java.io.File dir = new java.io.File(filePath);
        List<java.io.File> fileList = new ArrayList<>();
        java.io.File[] files = dir.listFiles();

        if (files != null) {
            for (java.io.File file : files) {
                if (file.isDirectory()) {
                    fileList.addAll(allFiles(file.getAbsolutePath()));
                } else {
                    fileList.add(file);
                }
            }
        }
        return fileList;
    }
}
